﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using IWMAG.Scripting.AST.ObjectModel;
using IWMAG.Scripting.Types;
using IWMAG.Scripting.Compiler.UserInfo;

namespace IWMAG.Scripting.AST.Declarations {
    public class VariableDeclaration : CodeDeclaration {
        public CodeType Type;
        public string Name;
        public CodeExpression InitialValue;

        public VariableDeclaration(Compiler.Lexeme l, CodeType type, string name, CodeExpression val = null)
            : base(l) {
            Type = type;
            Name = name;
            InitialValue = val;
        }

        public override void Verify(Helpers.CompileTable sym, List<Compiler.IUserInfo> error) {
            Type = sym.Dealias(Type);
            if (InitialValue != null) {
                InitialValue.Verify(sym, error);
                CodeType t = sym.Dealias(InitialValue.TypeOf());
                if (Type == CodeType.Auto) {
                    Type = t;
                } else if (!Type.Equals(t)) {
                    SendError(error, Rules.IncompatibleTypesInAssignment, t.ToString(), Type.ToString());
                }
            } else if (Type == CodeType.Auto) {
                SendError(error, Rules.TypeInferredVariableMustBeInitialized, Name);
            }

            if (!sym.TypeExists(Type)) {
                SendError(error, Rules.UseOfUnresolvedType, Type.ToString());
            }
        }
    }
}
